---
comments: false
disable_fancybox: false
---

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Combine Images</title>
    <script src="https://cdn.jsdelivr.net/npm/leancloud-storage/dist/av-min.js"></script>
    <script src="../leancloud.js"></script>
    <script src="../js/shufaDictJS.js"></script>
    <link rel="stylesheet" href="../css/shufaDictCSS.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.min.js"></script>
    <style>
        #dropArea {
            margin: 20px 0;
            padding: 10px;
            background-color: #fff;
            border: 2px dashed #007bff;
            border-radius: 5px;
            width: calc(100% - 44px);
            /* Adjust width for padding and border */
            cursor: pointer;
        }

        #dropArea.highlight {
            background-color: #f0f0f0;
            /* Light grey background */
            border: 2px dashed #000;
            /* Dashed border */
        }

        button {
            background-color: #007bff;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-right: 10px;
            font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
        }

        button:hover {
            background-color: #0056b3;
        }

        .progress-container {
            width: 100%;
            background-color: #eee;
            margin: 20px 0;
            height: 20px;
            border-radius: 5px;
        }

        .progress-bar {
            height: 100%;
            background-color: #007bff;
            width: 0%;
            /* Initial width */
            border-radius: 5px;
            text-align: center;
            color: white;
            line-height: 20px;
            /* To center text vertically */
        }

        #canvas {
            border: 0px solid #000;
            margin-top: 10px;
            width: 100%;
            height: auto;
            /* Adjust based on your needs */
        }

        #downloadLink {
            display: block;
            cursor: pointer;
        }

        #title {
            text-align: center;
            flex: 2;
            text-align: center;
            font-weight: bold;
        }

        #loading_overlay {
            display: flex;
            justify-content: center;
            align-items: center;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            /* 半透明背景 */
        }

        #loadingImage {
            max-width: 100%;
            max-height: 100%;
        }
        #buttonContainer2 {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            max-width: 1200px; /* 可以根据需要调整 */
            margin: 0 auto; /* 水平居中 */
        }
        #switchButton {
            background-color: var(--main-color);
        }
    </style>
</head>

<body>
    <div id="buttonContainer">
        <div id="backButton"></div>
        <div id="title"></div>
        <a id="downloadLink" onclick="addDownloadButton()" >下载图片</a>
    </div>

    <div id="buttonContainer2">
        
        <button id="switchButton" onclick="addToggleButton()">切换方向</button>
        
    </div>
    
    <!-- <h1>Image Stitcher</h1> -->
    <!-- <div id="dropArea">
        <p>Drag and drop images here or click to select</p>
        <input type="file" multiple id="fileInput" style="display: none;">
    </div>
    <button onclick="combineImages()">Combine Images</button>
    <button onclick="resetCanvas()">Reset</button> -->
    <!-- <div class="progress-container">
        <div class="progress-bar" id="progressBar"></div>
    </div> -->
    <!-- <a id="downloadLink" href="#" style="display:none;">下载图片</a>
    <br> -->
    <canvas id="canvas"> </canvas>
    <div id="loading_overlay">
        <img id="loadingImage" src="../images/grid.svg" />
    </div>

    <script>

        initLeanCloud()
        let blob = null;
        let canvasWidth = 0;
        let canvasHeight = 0;
        let isHorizontal = false;
        var loading_overlay = document.getElementById('loading_overlay');
        loading_overlay.style.display = 'flex';
        var img = document.getElementById('backButton');
        var title = document.getElementById('title');
        img.addEventListener('click', function () {
            window.history.back()
        });
        function switchOrientation() {
            addToggleButton()
        }
        // 在页面加载时调用此函数
        addToggleButton();
        // 添加切换按钮的函数
        function addDownloadButton() {
            if (blob == null) {
                return
            }
            uploadImg(blob)
        }
        function addToggleButton() {
            const button = document.getElementById('switchButton');
            // button.textContent = '切换拼接方向';
            button.onclick = function () {
                isHorizontal = !isHorizontal;
                combineImages();
            };

            const canvas = document.getElementById('canvas');
            if (canvas && canvas.parentNode) {
                canvas.parentNode.insertBefore(button, canvas);
            } else {
                // 如果找不到 canvas 或其父元素，就将按钮添加到 body 的开头
                document.body.insertBefore(button, document.body.firstChild);
            }
        }
        async function combineImages() {
            var imageUrls = JSON.parse(localStorage.getItem('selectedImageUrls')) || [];
            const images = [];
            const texts = [];
            imageUrls.forEach(function (dic, index) {
                images.push(dic.dict_img),
                    texts.push(dic.dict_name)
            });
            title.innerHTML = texts.join('');
            if (images.length < 1) {
                alert('图片数组为空。');
                return;
            }
            let loadedImages = [];
            for (let i = 0; i < images.length; i++) {
                try {
                    const dataUrl = await loadImageAsDataUrl(images[i]);
                    const img = new Image();
                    img.src = dataUrl;
                    await new Promise((resolve, reject) => {
                        img.onload = resolve;
                        img.onerror = reject;
                    });
                    loadedImages.push(img);
                } catch (error) {
                    console.error('加载图片失败：', error);
                    alert('加载图片失败：' + images[i]);
                }
            }
            // 继续处理加载好的图片...
            let totalHeight = 0;
            let minWidth = Infinity;

            let totalWidth = 0;
            let maxHeight = 0;
            // 找出最小宽度
            loadedImages.forEach(img => {
                minWidth = Math.min(minWidth, img.width);
            });

            if (isHorizontal) {
                // 计算总宽度和最大高度
                loadedImages.forEach(img => {
                    totalWidth += img.width;
                    maxHeight = Math.max(maxHeight, img.height);
                });
            } else {
                // 计算调整后的总高度
                loadedImages.forEach(img => {
                    let aspectRatio = img.height / img.width;
                    let newHeight = minWidth * aspectRatio;
                    totalHeight += newHeight;
                });
            }

            renderImages(loadedImages, isHorizontal ? totalWidth : minWidth, isHorizontal ? maxHeight : totalHeight);
        }
        async function loadImageAsDataUrl(url) {
            const proxyUrl = `https://proxyimage.lintiebao.cn/proxy?url=${encodeURIComponent(url)}`;
            const response = await fetch(proxyUrl);
            const blob = await response.blob();
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onloadend = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            });
        }
        async function renderImages(images, canvasWidth, canvasHeight) {
            const canvas = document.getElementById('canvas');
            if (!canvas) {
                console.error('找不到 canvas 元素');
                alert('无法渲染图像：找不到 canvas 元素');
                return;
            }
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                console.error('无法获取 canvas 2D 上下文');
                alert('无法渲染图像：canvas 上下文不可用');
                return;
            }
            const maxWidth = 3000; // 设置最大宽度
            let totalWidth = 0;
            let totalHeight = 0;
            let commonWidth = 0;
            let commonHeight = 0;

            if (isHorizontal) {
                // 横向拼接：找出最小高度
                commonHeight = Math.min(...images.map(img => img.height));
                images.forEach(img => {
                    let aspectRatio = img.width / img.height;
                    totalWidth += commonHeight * aspectRatio;
                });
                // 如果总宽度超过最大宽度，进行缩放
                if (totalWidth > maxWidth) {
                    let scale = maxWidth / totalWidth;
                    commonHeight *= scale;
                    totalWidth = maxWidth;
                }
                canvas.width = totalWidth;
                canvas.height = commonHeight;
            } else {
                // 竖直拼接：使用传入的 canvasWidth
                commonWidth = canvasWidth;
                images.forEach(img => {
                    let aspectRatio = img.height / img.width;
                    totalHeight += commonWidth * aspectRatio;
                });
                canvas.width = commonWidth;
                canvas.height = totalHeight;
            }
            let offset = 0;
            for (let img of images) {
                if (isHorizontal) {
                    let imgWidth = (img.width / img.height) * commonHeight;
                    ctx.drawImage(img, offset, 0, imgWidth, commonHeight);
                    offset += imgWidth;
                } else {
                    let imgHeight = (img.height / img.width) * commonWidth;
                    ctx.drawImage(img, 0, offset, commonWidth, imgHeight);
                    offset += imgHeight;
                }
            }
            blob = await new Promise(resolve => canvas.toBlob(resolve));
            self.canvasWidth = canvasWidth;
            self.canvasHeight = canvasHeight;
            if (typeof loading_overlay !== 'undefined' && loading_overlay) {
                loading_overlay.style.display = 'none';
            }
            
            confetti({
                particleCount: 100,
                spread: 70,
                origin: { y: 0.6 }
            });

            // uploadImg(blob)
        }
        async function uploadImg(blob) {
            const file = new AV.File('combined_image.png', blob);

            try {
                // 设置文件的过期时间（10分钟后）
                const expirationTime = new Date(new Date().getTime() + 10 * 60 * 1000);
                file.set('expirationTime', expirationTime);
                // 保存文件（只保存一次）
                const savedFile = await file.save();
                const imageUrl = savedFile.url();
                // 展示图片
                displayImage(imageUrl, canvasWidth, canvasHeight);
                // 存储文件对象ID,用于后续删除
                window.combinedImageId = savedFile.id;
                console.log('图片上传成功，URL:', imageUrl);

                
            } catch (error) {
                console.error('上传图片失败:', error);
                alert('上传图片失败: ' + error.message);
            }
        }
        // 删除图片的函数
        // async function deleteImage(fileId) {
        //     if (fileId) {
        //         try {
        //             const file = AV.File.createWithoutData(fileId);
        //             await file.destroy();
        //             console.log('图片已从LeanCloud删除');
        //         } catch (error) {
        //             console.error('删除图片失败:', error);
        //         }
        //     }
        // }
        function displayImage(url, width, height) {
            const img = new Image();
            img.onload = function () {
                const canvas = document.getElementById('canvas');
                if (canvas && canvas.parentNode) {
                    const container = canvas.parentNode;
                    container.replaceChild(img, canvas);
                } else {
                    document.body.appendChild(img);
                }

                // 设置img的样式
                img.style.maxWidth = '100%';
                img.style.maxHeight = '80vh';
                img.style.width = 'auto';
                img.style.height = 'auto';
                img.style.display = 'block';
                img.style.marginLeft = 'auto';
                img.style.marginRight = 'auto';
            };
            img.onerror = function () {
                console.error('图片加载失败');
            };
            img.src = url;
            if (typeof loading_overlay !== 'undefined' && loading_overlay) {
                loading_overlay.style.display = 'none';
            }
            const button = document.getElementById('switchButton');
            button.style.display = 'none';
            Swal.fire({
                text: '长按图片分享或保存至手机相册！',
                confirmButtonText: '确定',
                // cancelButtonText: '取消',
                // showCancelButton: true, // 显示取消按钮
                reverseButtons: true,
                // 自定义样式
                customClass: {
                    container: 'custom-swal-container',
                    popup: 'custom-swal-popup',
                    // 修改标题样式
                    title: 'custom-swal-title',
                    // 修改内容文字样式
                    content: 'custom-swal-content',
                    // 修改确认按钮样式
                    confirmButton: 'custom-swal-confirm-button',
                    // 修改取消按钮样式（如果有的话）
                    cancelButton: 'custom-swal-cancel-button'
                },
                // 直接应用内联样式
                buttonsStyling: false, // 禁用默认的按钮样式
            })
        }
        document.addEventListener('DOMContentLoaded', function () {
            var dropArea = document.getElementById('dropArea');
            var fileInput = document.getElementById('fileInput'); // Make sure this matches the ID of your file input

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            function highlight(e) {
                dropArea.classList.add('highlight');
            }

            function unhighlight(e) {
                dropArea.classList.remove('highlight');
            }

            function handleDrop(e) {
                var dt = e.dataTransfer;
                var files = dt.files;

                fileInput.files = files;
                combineImages();
            }
        });
        function resetCanvas() {
            // Clear the file input
            var fileInput = document.getElementById('fileInput');
            fileInput.value = "";

            // Clear the canvas
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // Hide the download link
            // var downloadLink = document.getElementById('downloadLink');
            // downloadLink.style.display = 'none';

            // Optionally, reset other elements on the page as needed
        }

        combineImages()
        hiddenEle()

    </script>
</body>

</html>